package com.hongdee.insurance.quotation.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.car.service.ITCrmCarService;
import com.hongdee.insurance.Constant;
import com.hongdee.insurance.car.entity.TInsuranceCar;
import com.hongdee.insurance.car.service.ITCrmCarWarningConfService;
import com.hongdee.insurance.car.service.ITInsuranceCarService;
import com.hongdee.insurance.company.entity.TInsuranceCompany;
import com.hongdee.insurance.company.service.ITInsuranceCompanyService;
import com.hongdee.insurance.order.controller.TinsuranceCommissionExamController;
import com.hongdee.insurance.quotation.dao.ITInsuranceQuotationDao;
import com.hongdee.insurance.quotation.entity.TInsuranceQuotation;
import com.hongdee.insurance.quotation.mapper.ITInsuranceQuotationMapper;
import com.hongdee.insurance.quotation.pojo.TInsuranceQuotationItemPojo;
import com.hongdee.insurance.quotation.pojo.TInsuranceQuotationPojo;
import com.hongdee.insurance.quotation.service.ITInsuranceQuotationService;
import com.hongdee.insurance.quotationitem.entity.TInsuranceQuotationItem;
import com.hongdee.insurance.quotationitem.service.ITInsuranceQuotationItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/4/26.
 */
@Service
public class TInsuranceQuotationServiceImpl implements ITInsuranceQuotationService {
    @Autowired
    private ITInsuranceQuotationDao itInsuranceQuotationDao;
    @Autowired
    private ITInsuranceCarService carService;
    @Autowired
    private ITCrmCarWarningConfService warningConfService;

    @Autowired
    private ITInsuranceQuotationItemService quotationItemService;
    @Autowired
    private ITCrmCarService crmCarService;

    @Autowired
    private ITInsuranceQuotationMapper quotationMapper;
    @Autowired
    private ITInsuranceCompanyService companyService;

    private String tabName = "T_Insurance_Quotation";
    private String tabEntity = "TInsuranceQuotationController";
    private String tabInsurance = "T_INSURANCE_CAR";

    /**
     * 保险报价单分页查询
     *
     * @param uid
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map page(String uid, String start, String limit, Map data) throws Exception {
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        this.quotationQueryToSql(sql,params,data,uid);
        return this.itInsuranceQuotationDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 详细信息
     * @param qid
     * @return
     * @throws Exception
     */
    @Override
    public Map getQuotationInfo(String qid,String uid) throws Exception {
        StringBuffer sql=new StringBuffer();
        List params=new ArrayList();
        Map map=new HashMap();
        map.put("qid",qid);
        this.quotationQueryToSql(sql,params,map,uid);
        return this.itInsuranceQuotationDao.info(sql.toString(),params.toArray());
    }
    private void quotationQueryToSql(StringBuffer sql,List params,Map data,String uid){
        sql.append("select * from (select tc.*,tq.id qid,tic.insurance_company_name,tq.insurance_company_id,tq.insurance_start_date,")
                .append("tq.status,tq.insurance_stop_date,tq.compulsory_total,tq.insure_type,tq.commercialinsurance_total, " +
                        "tq.commercialinsurance_discount, tq.compulsory_discount, ")
                .append("ceil(TIMESTAMPDIFF(DAY,tc.first_record_Date, NOW())/365) age, " +
                        " (select COUNT(quotation_id) from t_insurance_quotation_item where quotation_id=tq.id group by quotation_id) items," +
                        " tq.company_id as quCompanyId,tq.create_time as time," +
                        " tq.store_chanel,tq.store_p_area,tq.store_area_code,tq.store_code,tq.store_p_area_code " +
                        " from " + tabName  )
                .append(" tq left join " +tabInsurance +" tc on tq.car_id = tc.id ")
                .append(" left join T_Insurance_Company tic on tq.insurance_company_id = tic.id ) as temp");

        sql.append(" where 1=1 ");
//        if(!"".equals(StringUtil.formatEmpty(data.get("companyId")))){
        sql.append(" and temp.company_id=? ");
        params.add(TokenUtil.getCompanyId(uid));
//        }else{
//            Constant.setQueryByRoleDate(uid,sql,params,"temp");
//        }
        if(!"".equals(StringUtil.formatEmpty(data.get("vin")))){
            sql.append(" and temp.vin=? ");
            params.add(StringUtil.formatEmpty(data.get("vin")));
        }
        //筛选保险公司名称
        if (data.get("plateNum") != null && !data.get("plateNum").equals("")) {
            sql.append(" and ( temp.plate_num like ? or temp.vin like ? ) ");
            params.add("%" + data.get("plateNum") + "%");
            params.add("%" + data.get("plateNum") + "%");
        }
        //保险公司名称
        if(!"".equals(StringUtil.formatEmpty(data.get("insuranceCompanyName")))){
            sql.append(" and temp.insurance_company_name like ? ");
            params.add("%"+StringUtil.formatEmpty(data.get("insuranceCompanyName"))+"%");
        }
        //联系人
        if(!"".equals(StringUtil.formatEmpty(data.get("insured")))){
            sql.append(" and temp.insured like ? ");
            params.add("%"+StringUtil.formatEmpty(data.get("insured"))+"%");
        }
        //电话
        if(!"".equals(StringUtil.formatEmpty(data.get("contactPhone")))){
            sql.append(" and temp.contact_phone like ? ");
            params.add("%"+StringUtil.formatEmpty(data.get("contactPhone"))+"%");
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("qid")))){
            sql.append(" and temp.qid=? ");
            params.add(StringUtil.formatEmpty(data.get("qid")));
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("startDate")))){
            sql.append(" and temp.insurance_start_date>=? ");
            params.add(StringUtil.formatEmpty(data.get("startDate")));
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("stopDate")))){
            sql.append(" and temp.insurance_start_date<=? ");
            params.add(StringUtil.formatEmpty(data.get("stopDate")));
        }
        sql.append(" order by temp.time desc ");
    }


    /**
     * 保险报价单明细
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择保险公司！");
        }
        String sql = "select tc.id,tc.insured,tc.insured_address,tc.insured_ID_number insuredIdNumber, model.model_name car_model,tc.car_type,tc.contact_name,  " +
                "                 tc.contact_phone,tc.driver_license,tc.email,tc.engine_num,tc.first_record_date,tc.passenger_weight,  " +
                "                 tc.plate_num,tc.power,tc.real_value,tc.use_property,tc.vin,tc.post_code,tc.company_id,tc.car_age,tc.insurance_company,  " +
                "                 tc.insurance_end_date,tc.car_property,tc.sales_property,tc.car_brand,tc.car_configure,tc.car_series,  " +
                "                 tc.car_level,tc.car_age,tq.insurance_start_date,tq.insurance_stop_date,tq.compulsory_total,tq.commercialinsurance_total ";
        sql+="from "+tabName+" tq left join "+tabInsurance+" tc on tq.car_id=tc.id left JOIN t_bc_carmodel model on tc.car_model=model.id where tq.id = ? ";
        return this.itInsuranceQuotationDao.info(sql, new Object[]{id});
    }

    /**
     * 新增保险报价单
     *
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceQuotation saveOrUpdate(TInsuranceQuotation data, String uid, String insurance) throws Exception {
        TInsuranceQuotation quotation=null;
        /**结束时间自动加一年**/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(data.getInsuranceStartDate());

        Long l1=DateUtils.addMonthLongTime(dt.getTime(),+12);
        Long l2=DateUtils.addDayLongTime(l1,-1);
        data.setInsuranceStopDate(sdf.format(l2));
        if(data.getId()==null){
            quotation=new TInsuranceQuotation();
            BeanUtils.copyProperties(data,quotation);
            //判断同一车辆ID，在一个保险公司和保险起始日期，只能有一个报价单
            //判断insurance是否为0，为0时说明新增的客户档案为CRM中的车主档案查询过来，需要从CRM车主档案移至保险客户档案
            if("0".equals(insurance)){
                carService.addInsuranceCar(quotation.getCarId(),uid);
            }
            quotation.setCreateUser(uid);
            quotation.setCreateTime(System.currentTimeMillis());
            quotation.setStatus("0");
            quotation.setCompanyId(TokenUtil.getCompanyId(uid));
            quotation.setCommercialinsuranceTotal("0");
            quotation.setCompulsoryTotal("0");
        }else{
            quotation=this.getInsuranceQuotationById(data.getId());
            quotation.setUpdateTime(System.currentTimeMillis());
            quotation.setUpdateUser(uid);
            quotation.setCompulsoryTotal(data.getCompulsoryTotal());
            quotation.setCommercialinsuranceTotal(data.getCommercialinsuranceTotal());
            quotation.setInsuranceStartDate(data.getInsuranceStartDate());
            quotation.setInsuranceStopDate(data.getInsuranceStopDate());
        }
        TInsuranceCar car= carService.getCarInfo(quotation.getCarId());
        quotation.setVin(car.getVin());
        quotation.setPlateNum(car.getPlateNum());
        this.itInsuranceQuotationDao.saveOrUpdate(quotation);  // 保存、更新报价单
        return quotation;
    }

    @Override
    public boolean checkQuotationInfo(TInsuranceQuotation data) throws Exception {
        StringBuffer sql=new StringBuffer();
        sql.append(" select q.*,c.insurance_company_name from  T_Insurance_Quotation q,t_insurance_company c where q.insurance_company_id=c.id " +
                " and  q.car_id=? and q.insurance_company_id=?");

        List<Map<String, Object>> mapList=this.itInsuranceQuotationDao.list(sql.toString(),data.getCarId(),data.getInsuranceCompanyId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for(int i=0;i<mapList.size();i++){
            Map tempMap=mapList.get(i);
            Long begin = sdf.parse(String.valueOf(tempMap.get("insuranceStartDate"))).getTime();
            Long end = sdf.parse(String.valueOf(tempMap.get("insuranceStopDate"))).getTime();
            //新增佣金起止时间与历史数据起止时间重叠
            Long start=sdf.parse(data.getInsuranceStartDate()).getTime();
            Long stop=sdf.parse(data.getInsuranceStopDate()).getTime();
            String companyName=String.valueOf(tempMap.get("insuranceCompanyName"));
            boolean flag=true;
            if(begin<=start && end>=stop){
                flag=false;
            }
            if(begin<=start && end<=stop && end>start){
                flag=false;
            }
            if(end<=stop && begin>=start){
                flag=false;
            }
            if(begin>=start && end>=stop && begin<stop){
                flag=false;
            }
            if(!flag){
                throw new Exception("该车辆"+data.getInsuranceStartDate()+"至"+data.getInsuranceStopDate()+"在"+companyName+"已有报价单，请调整后重新录入！");
            }
        }
        return false;
    }



    /**
     * 报价单详情修改
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void update(Map data,String uid,String id)throws Exception{
        TInsuranceQuotation quotation=this.getInsuranceQuotationById(id);
        if(quotation!=null){
            quotation.setUpdateTime(System.currentTimeMillis());
            quotation.setUpdateUser(uid);
            quotation.setCompulsoryTotal(StringUtil.formatEmpty(data.get("compulsoryTotal")));
            quotation.setCommercialinsuranceTotal(StringUtil.formatEmpty(data.get("commercialinsuranceTotal")));
            quotation.setInsuranceStartDate(StringUtil.formatEmpty(data.get("insuranceStartDate")));
            quotation.setInsuranceStopDate(StringUtil.formatEmpty(data.get("insuranceStopDate")));
            quotation.setCoupulsoryDiscount(StringUtil.formatEmpty(data.get("coupulsoryDiscount")));
            quotation.setCommercialinsuranceDiscount(StringUtil.formatEmpty(data.get("commercialinsuranceDiscount")));
            if(!"".equals(quotation.getCommercialinsuranceTotal())) {
                Map carInfo=carService.getCarInfo(quotation.getCarId(),"",uid);
                String brand=StringUtil.formatEmpty(carInfo.get("carBrand"));
                String series=StringUtil.formatEmpty(carInfo.get("carSeries"));
                String model=StringUtil.formatEmpty(carInfo.get("carModel"));
                String configure=StringUtil.formatEmpty(carInfo.get("carConfigure"));
                quotation.setPriceWarningType(this.checkWarningConf(quotation.getCommercialinsuranceTotal(),uid,brand,series,model,configure));
            }else {
                quotation.setPriceWarningType("1");
            }
            //获得报价单交强险项目
            List<Map<String,Object>> jqItems=quotationItemService.findQuotationJqItem(quotation.getId());
            //获得报价单商业险项目
            List<Map<String,Object>> syItems=quotationItemService.findQuotationSyItem(quotation.getId());
            if(jqItems.size()>0 && syItems.size()==0){
                quotation.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()));
            }
            if(syItems.size()>0 && jqItems.size()==0){
                quotation.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
            }
            if(syItems.size()>0 && jqItems.size()>0){
                quotation.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()));
            }
            quotation.setCompulsoryTotal(Constant.formatFloat(getItemPrice(jqItems)).toString());
            quotation.setCommercialinsuranceTotal(Constant.formatFloat(getItemPrice(syItems)).toString());
            this.itInsuranceQuotationDao.saveOrUpdate(quotation);
        }
    }

    private Float getItemPrice(List<Map<String,Object>> items){
        Float f=0f;
        if(items!=null){
            if(items.size()>0){
                for(Map<String,Object> item:items){
                    f+=Float.valueOf(StringUtil.formatEmpty(item.get("itemPrice")));
                }
            }
        }
        return f;
    }

    /**
     * 佣金检测
     * @param syPrice
     * @param uid
     * @param brand
     * @param series
     * @param model
     * @param configure
     * @throws Exception
     */
    @Override
    public String checkWarningConf(String syPrice,String uid,String brand,String series,String model,
                                 String configure) throws Exception {
        String warningType="1";
//        Map warningMap = warningConfService.getWarningInfo(brand, series, model, configure);
//        if (warningMap != null) {
//            Float max = Float.valueOf(StringUtil.formatEmpty(warningMap.get("max")));
//            Float min = Float.valueOf(StringUtil.formatEmpty(warningMap.get("min")));
//            if (Float.valueOf(syPrice) > max) {
//                warningType="0";
//            }
//            if (Float.valueOf(syPrice) < min) {
//                warningType="0";
//            }
//            if (Float.valueOf(syPrice) >= min && Float.valueOf(syPrice) <= max) {
//                warningType="1";
//            }
//
//        } else {
//            warningType="0";
//        }
        return warningType;
    }

    /**
     * 根据ID 获得报价单详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceQuotation getInsuranceQuotationById(String id) throws Exception {
        return this.itInsuranceQuotationDao.getQuotationById(id);
    }

    /**
     * 删除报价单信息
     * @param id
     * @throws Exception
     */
    @Override
    public void delInsuranceById(String id,boolean del) throws Exception {
        //获取报价单详情 如已出单 不允许删除
        TInsuranceQuotation quotation=getInfo(id);
        if(!del) {
            if ("2".equals(quotation.getStatus())) {
                throw new Exception("该报价单已出单，不允许删除!!");
            }
        }
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_quotation_item where quotation_id=?",id);
//        this.itInsuranceQuotationDao.executeSQL("delete from t_crm_car_coupon where id in (select id from t_insurance_order_coupon where quotation_id=?)",id);
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_order_coupon where quotation_id=?",id);
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_order_item where order_id in (select id from t_insurance_order where quotation_id=?)",id);
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_order where quotation_id=?",id);
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_quotation where id=?",id);
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_task where quotation_id=?",id);
        this.itInsuranceQuotationDao.executeSQL("delete from t_insurance_order_statistics where quotation_id=?",id);
    }

    /**
     * 根据车辆ID 交强险保费 判断是否超过车辆预警值
     * @param carId
     * @param syPrice
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map checkWarningByCar(String carId,Float syPrice,String uid) throws Exception {
        Map resultMap=new HashMap();
        resultMap.put("success",true);
        Map carInfo=carService.getCarInfo(carId,"",uid);
        if(carInfo==null){
            resultMap.put("success",false);
            resultMap.put("msg","未找到车辆信息!!");
            return resultMap;
        }
        String brand=StringUtil.formatEmpty(carInfo.get("carBrand"));
        String series=StringUtil.formatEmpty(carInfo.get("carSeries"));
        String model=StringUtil.formatEmpty(carInfo.get("carModel"));
        String configure=StringUtil.formatEmpty(carInfo.get("carConfigure"));
        Map warningMap=warningConfService.getWarningInfo(brand,series,model,configure);
        if(warningMap==null){
            resultMap.put("success",false);
            resultMap.put("msg","未找到保费预警信息，是否继续保存?");
            return resultMap;
        }
        Float max=Float.valueOf(StringUtil.formatEmpty(warningMap.get("max")));
        Float min=Float.valueOf(StringUtil.formatEmpty(warningMap.get("min")));
        if(syPrice>max){
            resultMap.put("success",false);
            resultMap.put("msg","商业险价格："+syPrice+" 超过预警最高价格，最大值为："+max+"，请注意!!");
        }
        if(syPrice<min){
            resultMap.put("success",false);
            resultMap.put("msg","商业险价格："+syPrice+" 低于预警最低价格，最低值为："+min+"，请注意!!");
        }
        if(syPrice>=min && syPrice<=max){
            resultMap.put("success",true);
            resultMap.put("msg","验证成功!!");
        }
        return resultMap;
    }

    @Override
    public TInsuranceQuotation getInfo(String id) throws Exception {
        return this.itInsuranceQuotationDao.getQuotationById(id);
    }

    /**
     * 更新报价单
     * @param quotation
     * @throws Exception
     */
    @Override
    public void update(TInsuranceQuotation quotation) throws Exception {
        this.itInsuranceQuotationDao.saveOrUpdate(quotation);
    }

    /**
     * 解析壁虎车险读取的车辆报价信息
     * @param uid
     * @param plateNum
     * @param bihuMap
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void analyzeBiHuMsg(String uid,String plateNum,Map<String,Object> bihuMap) throws Exception {
        String companyId="0";//TokenUtil.getCompanyId(uid);
        //1、查询车辆信息，根据车牌号
        Map<String,Object> carMap=crmCarService.findById(plateNum,"",companyId);
        if(carMap!=null) {
            if(carMap.size()>0) {
                //1、解析 创建报价单信息
                Map userInfo= (Map) bihuMap.get("UserInfo");
                Map dateMap=(Map)userInfo.get("PostStartDate");
                TInsuranceQuotationPojo quotation=new TInsuranceQuotationPojo();
                quotation.setId(StringUtil.UUID());
                Float syTotal=0f;
                Float jqTotal=0f;
                //2、解析资源信息
                Map<String,Object> Item=(Map<String,Object>)bihuMap.get("Item");
                List<TInsuranceQuotationItemPojo> quotationItems=new ArrayList<>();
                Map<String,Object> biHueItemMap=this.getItemIdByBihu();
                for (String key : Item.keySet()) {
                    if(Item.get(key) instanceof HashMap) {
                        Map<String, Object> itemLimit = (Map<String, Object>) Item.get(key);
                        String baoe = "0";
                        if (itemLimit.get("BaoE") != null) {
                            baoe = StringUtil.formatEmpty(itemLimit.get("BaoE"));
                        }
                        String baoFei = "0";
                        if (itemLimit.get("BaoFei") != null) {
                            baoFei = StringUtil.formatEmpty(itemLimit.get("BaoFei"));
                        }
                        if (!baoFei.equals("0")) {
                            TInsuranceQuotationItemPojo quotationItem = (TInsuranceQuotationItemPojo) biHueItemMap.get(key);
                            quotationItem.setItemPrice(baoFei);
                            quotationItem.setItemLimit(baoe);
                            quotationItem.setQuotationId(quotation.getId());
                            quotationItems.add(quotationItem);
                            syTotal += Float.valueOf(baoFei);
                        }
                    }
                }
                if(!"0".equals(StringUtil.formatEmpty(Item.get("TaxTotal")))){
                    jqTotal+=Float.valueOf(StringUtil.formatEmpty(Item.get("TaxTotal")));
                    quotationItems.add(new TInsuranceQuotationItemPojo("0","交强险-车船使用税",
                            StringUtil.formatEmpty(Item.get("TaxTotal")),"",quotation.getId()));
                }
                if(!"0".equals(StringUtil.formatEmpty(Item.get("ForceTotal")))){
                    jqTotal+=Float.valueOf(StringUtil.formatEmpty(Item.get("ForceTotal")));
                    quotationItems.add(new TInsuranceQuotationItemPojo("1","交强险-保险费",
                            StringUtil.formatEmpty(Item.get("ForceTotal")),"",quotation.getId()));
                }
                TInsuranceCompany insuranceCompany=getInsuranceCompany(StringUtil.formatEmpty(Item.get("Source")));
                saveQuotationInfos(quotation,syTotal,jqTotal,companyId,carMap,Item,dateMap,insuranceCompany);
                saveQuotationItems(quotation,quotationItems,insuranceCompany);
            }

        }
    }
/**
 * @Name: 通过壁虎信息更新车辆数据
 * @Author: Liu XiaoLong
 * @Date: 2018/2/2 17:18
 * @Remark:
 */
    @Override
    public void updateCarInfoByBIHU(String uid, String plateNum, Map<String, Object> map) throws Exception {
        //String companyId = TokenUtil.getCompanyId(uid);
        String dataStr = (String) map.get("data");
        JSONObject dataMap = JSON.parseObject(dataStr);
        Map carInfo = (Map) dataMap.get("UserInfo");
        String vin = (String) carInfo.get("CarVin");
        String birthday = (String) carInfo.get("OwnerBirthday");
        String IdCard = (String) carInfo.get("HolderIdCard");
        List params = new ArrayList();
        List listSet = new ArrayList();
        if(!vin.equals("")){
            listSet.add(" b_vin = '"+vin+"' ");
        }
        /*if(!birthday.equals("")){
            listSet.add(" owner_birthday = '"+birthday+"' ");
        }else {*/
            if(IdCard != null && !IdCard.equals("")){
                String year = IdCard.substring(6,10);
                String month = IdCard.substring(10,12);
                String day = IdCard.substring(12,14);
                String birth = year+"年"+month+"月"+day+"日00时00分00秒";
                Long LBirth = DateUtils.DateStrToLong(birth);
                listSet.add(" owner_birthday = ? ");
                params.add(LBirth);
            }
        //}
        if(listSet.size()>0){
            String sqlSet = "";
            for(int i=0;i<listSet.size();i++){
                if(i!=0){
                    sqlSet += ",";
                }
                sqlSet += listSet.get(i);
            }
            String sql = "UPDATE t_crm_car SET "+sqlSet+" WHERE  company_id = ?  AND plate_num = ? ";

            params.add("0");
            params.add(carInfo.get("LicenseNo"));
            itInsuranceQuotationDao.executeSQL(sql,params.toArray());
        }
        else {
            System.out.println("车牌号["+carInfo.get("plate_num")+"]不更新数据");
        }
    }


    /**
     * 设置报价单信息，并保存
     * @param quotation
     * @param syTotal
     * @param jqTotal
     * @param companyId
     * @param carMap
     * @param Item
     * @param dateMap
     * @throws Exception
     */
    private void saveQuotationInfos(TInsuranceQuotationPojo quotation,Float syTotal,Float jqTotal,String companyId,
                                   Map<String,Object> carMap,Map<String,Object> Item,Map<String,Object> dateMap,
                                    TInsuranceCompany insuranceCompany) throws Exception {
        quotation.setCreateTime(String.valueOf(System.currentTimeMillis()));
        quotation.setPlateNum(StringUtil.formatEmpty(carMap.get("plateNum")));
        quotation.setVin(StringUtil.formatEmpty(carMap.get("vin")));
        quotation.setCarId(StringUtil.formatEmpty(carMap.get("id")));
        quotation.setCommercialinsuranceTotal(syTotal.toString());
        quotation.setCompulsoryTotal(jqTotal.toString());
        quotation.setCompanyId(companyId);
        quotation.setContactPhone(StringUtil.formatEmpty(carMap.get("carownerTel")));
        quotation.setContactPeople(StringUtil.formatEmpty(carMap.get("carownername")));
        quotation.setCarId(StringUtil.formatEmpty(carMap.get("carId")));
        quotation.setStatus("0");
        quotation.setStoreArea(StringUtil.formatEmpty(carMap.get("storeArea")));
        quotation.setStoreAreaCode(StringUtil.formatEmpty(carMap.get("storeAreaCode")));
        quotation.setStoreCode(StringUtil.formatEmpty(carMap.get("storeCode")));
        quotation.setStoreChanel(StringUtil.formatEmpty(carMap.get("storeChanel")));
        quotation.setStoreName(StringUtil.formatEmpty(carMap.get("storeName")));
        quotation.setStoreParea(StringUtil.formatEmpty(carMap.get("storeParea")));
        quotation.setStorePareaCode(StringUtil.formatEmpty(carMap.get("storePareaCode")));

        quotation.setInsuranceCompanyId(insuranceCompany.getId());
        if(syTotal>0){
            quotation.setInsuranceStartDate(StringUtil.formatEmpty(dateMap.get("BusinessStartDate")).substring(0,10));
        }else if(jqTotal>0){
            quotation.setInsuranceStartDate(StringUtil.formatEmpty(dateMap.get("ForceStartDate")).substring(0,10));
        }
        if(syTotal==0 && jqTotal==0){
            throw new Exception("交强 商业保额皆为0，无法生成报价单!!");
        }
        quotation.setInsuranceStopDate(DateUtils.formatLongTimeByYYYYMMDD(DateUtils.addDayLongTime(DateUtils.
                addMonthLongTime(DateUtils.dayToLongTime(quotation.getInsuranceStartDate()),+12),-1)));
        quotation.setInsureType(StringUtil.formatEmpty(Constant.INSURE_TYPE.xb.ordinal()));
        if(syTotal>0 && jqTotal>0){
            quotation.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.all.ordinal()));
        }
        if(syTotal>0 && jqTotal==0){
            quotation.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()));
        }
        if(syTotal==0 && jqTotal>0){
            quotation.setIscompulsoryinsurance(String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()));
        }
        quotationMapper.saveQuotation(quotation);
    }


    /**
     *
     * @param quotation
     * @param quotationItems
     * @param company
     */
    private void saveQuotationItems(TInsuranceQuotationPojo quotation,List<TInsuranceQuotationItemPojo> quotationItems,
                                    TInsuranceCompany company){
        List<String> itemList=Constant.getBJMItemList();
        quotationMapper.delQuotationItemByQId(quotation.getId());
        DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        Float f=0f;
        for(TInsuranceQuotationItemPojo i:quotationItems){
            if(String.valueOf(Constant.COMPANY_TEMPLET.hebin.ordinal()).equals(company.getTemplet())){
                String itemId=i.getItemId();
                if(itemList.contains(itemId)){
                    f+=Float.valueOf(i.getItemPrice());
                }
            }
            quotationMapper.saveQuotationItem(i);
        }
        quotationMapper.saveQuotationItem(new TInsuranceQuotationItemPojo("25","不计免赔",
                decimalFormat.format(f),"",quotation.getId()));
    }

    /**
     * 获取保险公司信息
     * @param source
     * @return
     * @throws Exception
     */
    private TInsuranceCompany getInsuranceCompany(String source) throws Exception {
        Map<String,String> sourcesMap=new HashMap<>();
        sourcesMap.put("4096","");
        sourcesMap.put("2048","ff8081815e7109ca015e753a721b186c");
        sourcesMap.put("32","ff8081815e7b73db015e7e3cf2f70ac9");
        //sourcesMap.put("8","ff8081815e7b73db015e7e39b9770a70");
        sourcesMap.put("256","ff8081815f942b3e015f94b317a16027");
        //sourcesMap.put("2","8a80cb816007a014016007c1fb37002b");
        //sourcesMap.put("4","ff8081815e7109ca015e74bf4d3b6ef7");
        sourcesMap.put("64","ff8081815e7b73db015e7e3ef5710ad5");
        sourcesMap.put("512","ff8081815fc99482015fddb3a35d3bee");
        sourcesMap.put("128","ff8081815f99e89c015f9e344b954245");
        //sourcesMap.put("1","ff8081815e7109ca015e738c428803ed");
        sourcesMap.put("1","8a80cb816007a014016007c1fb37002b");
        sourcesMap.put("2","8a9aa28460247317016024a96f89000f");
        sourcesMap.put("4","8a80cb816007a014016007c2474d002c");
        sourcesMap.put("8","8a9aa28460247317016024a8b4f3000d");

        sourcesMap.put("1024","ff8081815fc99482015fe1a7ed865185");
        return companyService.getInfo(StringUtil.formatEmpty(sourcesMap.get(source)));
    }

    /**
     * 转换壁虎车险所对应的保险项目信息
     * @return
     */
    private Map getItemIdByBihu(){
        Map<String,Object> itemMap=new HashMap<>();
        itemMap.put("CheSun",new TInsuranceQuotationItemPojo("2","车辆损失险","","",""));
        itemMap.put("BuJiMianCheSun",new TInsuranceQuotationItemPojo("3","车辆损失险不计免赔","","",""));
        itemMap.put("SanZhe",new TInsuranceQuotationItemPojo("4","第三者责任险","","",""));
        itemMap.put("BuJiMianSanZhe",new TInsuranceQuotationItemPojo("5","第三者责任险不计免赔","","",""));
        itemMap.put("DaoQiang",new TInsuranceQuotationItemPojo("6","盗抢险","","",""));
        itemMap.put("BuJiMianDaoQiang",new TInsuranceQuotationItemPojo("7","盗抢险不计免赔","","",""));
        itemMap.put("SiJi",new TInsuranceQuotationItemPojo("8","车上人员责任险-司机","","",""));
        itemMap.put("ChengKe",new TInsuranceQuotationItemPojo("9","车上人员责任险-乘客","","",""));
        itemMap.put("BuJiMianSiJi",new TInsuranceQuotationItemPojo("10","车上人员责任险-司机-不计免赔","","",""));
        itemMap.put("BuJiMianChengKe",new TInsuranceQuotationItemPojo("11","车上人员责任险-乘客-不计免赔","","",""));
        itemMap.put("HuaHen",new TInsuranceQuotationItemPojo("12","车身划痕险","","",""));
        itemMap.put("BuJiMianHuaHen",new TInsuranceQuotationItemPojo("13","车身划痕险不计免赔","","",""));
        itemMap.put("ZiRan",new TInsuranceQuotationItemPojo("14","自燃损失险","","",""));
        itemMap.put("BuJiMianZiRan",new TInsuranceQuotationItemPojo("15","自燃损失险不计免赔","","",""));
        itemMap.put("SheShui",new TInsuranceQuotationItemPojo("16","发动机涉水险","","",""));
        itemMap.put("BuJiMianSheShui",new TInsuranceQuotationItemPojo("17","发动机涉水险-不计免赔","","",""));
        itemMap.put("BoLi",new TInsuranceQuotationItemPojo("18","玻璃单独玻璃险","","",""));
        itemMap.put("",new TInsuranceQuotationItemPojo("20","机动车损失保险无法找到第三方特约险","","",""));
        itemMap.put("HcHuoWuZeRen",new TInsuranceQuotationItemPojo("21","车上货物责任险","","",""));
        itemMap.put("CheSun",new TInsuranceQuotationItemPojo("23","续保手册","","",""));
        itemMap.put("CheSun",new TInsuranceQuotationItemPojo("24","驾意险","","",""));
//        itemMap.put("",new TInsuranceQuotationItem("25","不计免赔","","",""));
        itemMap.put("SheBeiSunShi",new TInsuranceQuotationItemPojo("26","新增设备险","","",""));
        itemMap.put("BjmSheBeiSunShi",new TInsuranceQuotationItemPojo("27","新增设备险不计免赔","","",""));
        return itemMap;
    }

    private Map<String,String> getInsuranceCompany(){
//        n == SourceType.PA ? t ? "中国平安保险" :
//                "平安" : n == SourceType.TPY ? t ? "中国太平洋保险" : "太平洋" : n == SourceType.RB ? t ? "中国人民保险" : "人保" : n == SourceType.GSC ? t ? "中国人寿财险" : "国寿财" : n == SourceType.ZHLH ? "中华联合" : n == SourceType.DADI ? "中国大地" : n == SourceType.SUN ? "中国阳光" : n == SourceType.TP ? "中国太平" : n == SourceType.HA ? "中国华安" : n == SourceType.TA ? "中国天安" : n == SourceType.YDTH ? "中国英大泰和" : n == SourceType.ASTP ? "中国安盛天平" : n == SourceType.ANXIN ? t ? "安心互联网车险" : "安心车险" : ""
        return null;
    }

}
